class Solution {
    int m, n;
    int[] dx = {1, -1, 0, 0};
    int[] dy = {0, 0, 1, -1};
    int[][] matrix;
    int[][] memo;//备忘录
    public int longestIncreasingPath(int[][] matrix_) {
        matrix = matrix_;
        m = matrix.length; n = matrix[0].length;
        memo = new int[m + 1][n + 1];
        int ret = 0;
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                ret = Math.max(ret, dfs(i, j));
            }
        }
        return ret;
    }
    public int dfs(int i, int j) {
        if(memo[i][j] != 0) return memo[i][j];
        int ret = 1;
        for(int k = 0; k < 4; k++) {
            int x = i + dx[k];
            int y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && matrix[x][y] > matrix[i][j]) {
                //求出当前位置的最长路径
                ret = Math.max(ret, dfs(x, y) + 1);
            }
        }
        memo[i][j] = ret;
        return ret;
    }
}